22. Exercise: Silent Mode

Exercise: Silent Mode

Now for the last piece of our puzzle we need to actually set the device to silent when a Geofence triggers an entry transition and change it back to normal when an exit transition is triggered!

Ever since Android N things have changed a little: Now to change Android’s ringer mode you need to have the right permissions, and unfortunately it’s slightly more complicated than the regular permissions we have dealt with before, like the location permission for example.

So let’s start with that.

First let’s add a checkbox to ask the user for RingerMode permissions, the onclick event will launch an intent for ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS and start it.

This intent launches a new built-in activity that allows the user to turn RingerMode permissions on or off for their apps. Once the user turns that on, they can then press back and continue to use the app.

To make sure our checkbox is always reflecting the correct permission status we need to initialize its state in onResume.

In case of Android N or later, we need to check if the permission was granted using isNotificationPolicyAccessGranted, otherwise we could assume that the permission is granted by default.

Also since we don’t want the user to be unchecking this after permissions have been granted, it's best to disable the checkbox once everything seems to be set properly.

Now let’s go back to our GeofenceBroadcastReceiver.

In onReceive, we can use GeofencingEvent.fromIntent to retrieve the GeofencingEvent that caused the transition.

From that we can call getGeofenceTransition to get the transition type.

And based on the transition type, we can use AudioManager to set the phone ringer mode.

To keep things modular. I’ve created this helper method setRingerMode that using an AudioManager can set the setRingerMode to either silent or normal based on the mode parameter passed in.
It also creates a NotificationManager to check for permissions for Android N or later.

Notifications

It would also be nice to have the app notify the user whenever the device has been set to silent or back to normal.

So I’ve created this helper method sendNotification that will create a typical Android notification with an icon corresponding to either being silent or normal.

Exercise Code

Exercise: T0X.05-Exercise-SilentMode

Exercise: Silent Mode

Task Description:

Okay, now it's your turn. Follow the steps to complete this coding exercise.

Task List:

Task Feedback:

Solution: [T0X.05-Solution-SilentMode][Diff]